package liuhe.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import liuhe.manager.ACManager;
import liuhe.manager.JiarunManager;
import liuhe.manager.YingtaiManager;
import liuhe.tools.Common;

public class YingtaiHttp {
	CloseableHttpClient httpclient = null;
	RequestConfig requestConfig = null;
	HttpClientContext clientContext = null;
	
	 String ADDRESS = "https://61e9-3048.aa2865.com";
	 String ADDRESSG = "";
	 String ACCOUNT = "";
	 String PWD = "";
	 String SC = "";
	 
	 String uid = "";
	 String installments = "";
	 String oldInstallments = "";
	 
	 public long canLoginTime;
	 private int statusCode = -1;
	 private String token = "";
	 String strCookies = "";
	public int getStatusCode() {
	    return statusCode;
	}
	
	int defaultTimeout = 60*1000;
	

	
	 {
		 
		    try {
		        // 创建一个信任所有证书的 TrustManager
		        TrustManager[] trustAllCerts = new TrustManager[]{
		            new X509TrustManager() {
		                public X509Certificate[] getAcceptedIssuers() {
		                    return null;
		                }
		                public void checkClientTrusted(X509Certificate[] certs, String authType) {
		                }
		                public void checkServerTrusted(X509Certificate[] certs, String authType) {
		                }
		            }
		        };

		        // 初始化 SSLContext
		        SSLContext sc = SSLContext.getInstance("TLS");
		        sc.init(null, trustAllCerts, new java.security.SecureRandom());

		        // 设置自定义的 SSLSocketFactory 和 HostnameVerifier
		        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);

			    requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
				   // requestConfig = RequestConfig.copy(requestConfig).setRedirectsEnabled(false).build();//禁止重定向 ， 以便获取cookieb18
				    
				   // requestConfig = RequestConfig.copy(requestConfig).setProxy(proxy).build();//使用代理
				    
				    requestConfig = RequestConfig.copy(requestConfig).setConnectTimeout(defaultTimeout).setConnectionRequestTimeout(defaultTimeout).setSocketTimeout(defaultTimeout).build();//设置超时
				        //httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
		        
		        // 配置 HttpClient 使用自定义的 SSLSocketFactory
		        httpclient = HttpClients.custom()
		                .setDefaultRequestConfig(requestConfig)
		                .setSSLSocketFactory(new org.apache.http.conn.ssl.SSLConnectionSocketFactory(sc))
		                .build();

		    } catch (Exception e) {
		        e.printStackTrace();
		    }
		 System.setProperty("https.protocols", "TLSv1.2");
		 System.setProperty("https.certificateVerification", "ignore");
		 HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
		 

	 }
	 
		public  void setLoginParams(String address, String account, String pwd, String sc){
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
			SC = sc;
		}
		
	    // 1成功	 -1登录失败, -2维护 , -3账号异常 , -4密码不正确 , 2抓取成功, 3抓取失败
	    public void updateStatusCode(int i) {

	    	if(i == -2) {
	    		canLoginTime = System.currentTimeMillis() + 1*1*1000;
	    	}
	    	

	    	//Common.logOut(ACCOUNT + "  update hg_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
	    	
	   	 statusCode = i;
	    
	    }
		
	    public long getCanLoginTime() {
	      	return canLoginTime;
	    }
	    
	    public  CloseableHttpResponse  execute(HttpUriRequest request) throws Exception{
	    	
	    	long time1 = System.currentTimeMillis();
	    	long time2 = System.currentTimeMillis();
	    	
	    	CloseableHttpResponse response;
	    	
	    	
	    	SimpleDateFormat dfsec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	
	    	
	    	try{
	    		Thread.sleep(100);
	    		//Thread.sleep(1200);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    	
	    	
	    	
	    	
	    	//Common.logOut("excecute time:" + dfsec.format(time1));
	    	
	    	
	    	try{
	    		response = httpclient.execute(request);    		
	    		time2 = System.currentTimeMillis();    		
	    		
	    	}catch(Exception e){
	    		
	    		time2 = System.currentTimeMillis();
	    		
	    		throw e;
	    	}
	    	

	    	
	    	return response;
	    	
	    }
	    
		public String setCookie(CloseableHttpResponse httpResponse)
		{
			//strCookies = "";
			//Common.logOut("----setCookieStore");
			Header headers[] = httpResponse.getHeaders("Set-Cookie");
			if (headers == null || headers.length==0)
			{
				//Common.logOut("----there are no cookies");
				return null;
			}

			String cookie = "";
			for (int i = 0; i < headers.length; i++) {
				cookie += headers[i].getValue();
				if(i != headers.length-1)
				{
					cookie += ";";
				}
			}
			String cookies[] = cookie.split(";");
			
			for (String c : cookies)
			{
				if(c.indexOf("path=") != -1 || c.indexOf("expires=") != -1 || c.indexOf("domain=") != -1 || c.indexOf("HttpOnly") != -1)
					continue;
				strCookies += c;
				strCookies += ";";
			}
			//Common.logOut("----setCookieStore success");

			return strCookies;
		}
	    
	    
	    public String doGet(String url, String cookies, String referUrl) {
	    	
	        try {  
	            // 创建httpget.    
	            HttpGet httpget = new HttpGet(url);
	            
	            if(cookies != "") {
	            	httpget.addHeader("Cookie",cookies);
	            }
	            httpget.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
	            httpget.addHeader("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
	            httpget.addHeader("Connection","keep-alive");	            
	            httpget.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	            

	            
	            //
	            
	            if(referUrl != "")
	            {
	            	httpget.addHeader("Referer",referUrl);
	            	
	            }
	            
	            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");           
	           // Common.logOut("executing request " + httpget.getURI()); 
	           
	            //设置超时
	            
//	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
//	            
//	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
//	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
//	            httpget.setConfig(requestConfigtmp);
	            
	            // 执行get请求.    
	            CloseableHttpResponse response = execute(httpget); 
	            
	            String statusLine = response.getStatusLine().toString();   
	            if(statusLine.indexOf("200 OK") == -1) {
	         	  // Common.logOut(statusLine); 
	            }
	            
	            try{
	            	setCookie(response);  	
	            	//Common.logOut("设置cookie:" + strCookies);
	            	
	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
	             	   return response.getFirstHeader("Location").getValue();
	                }
	                HttpEntity entity = response.getEntity(); 
	                
	                String res = EntityUtils.toString(entity);
	                
	                if(res != null && res.length() > 0 ){     
	                	//Common.logOut(res);
	                	
//	                	if(res.contains("logout_warn")) {
//	                		updateStatusCode(-1);
//	                	}
	                	
	                    return res;
	                }
	            }finally{
	                httpget.releaseConnection();
	                response.close();
	            }
	            

	            

	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (ParseException e) {  
	            e.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	        } catch (Exception e){
	        	e.printStackTrace();
	        }
	        
	        return null;
	    }
	    
	    public String doPost(String url,List<NameValuePair> formparams, String cookies, HttpPost httppost) {
	        return doPost(url, formparams,"UTF-8", cookies, httppost);
	    }

	    public String doPost(String url,List<NameValuePair> formparams,String charset, String cookies, HttpPost httppost) {


	     // 创建httppost   
	    	
	    	try {
	    	


	        //httppost.addHeader("Referer",ADDRESS+"/html/login/2022/");

	        if(formparams!=null) {
		        UrlEncodedFormEntity uefEntity;
		        
	            uefEntity = new UrlEncodedFormEntity(formparams, charset);
	            httppost.setEntity(uefEntity);
	        }

	            
	            
	            
	            
//	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
//	            
	//
//	            
//	            
//	            
//	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
//	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
//	            httppost.setConfig(requestConfigtmp);
	            
	            CloseableHttpResponse response = execute(httppost);
	            try {
	                // 打印响应状态    
	            	setCookie(response);
	            	//Common.logOut("设置cookie:" + strCookies);
	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
	            		String location = response.getFirstHeader("Location").getValue();
	            		//Common.logOut(response.getStatusLine());
	            		
	            		
	            		
	            		if(location != null) {
	            			return location;
	            		}
	            	}
	            	
	            	
	            	
	            	//Header headers[] = response.getHeaders("Content-Type");
	            	
	            	
	                HttpEntity entity = response.getEntity(); 
	                
	                String res = "";
	                
	                if(url.contains("get_today_ft_league_wager.php") || url.contains("app/ft/get_today_ft_allbets_wager.php")){            		
	                	res = new  String(EntityUtils.toString(entity).getBytes("ISO-8859-1"), "UTF-8");
	                }else{
	                	res = EntityUtils.toString(entity);
	                }
	                
	                
	                if(res != null && res.length() > 0 ){   

//	                	if(res.contains("logout_warn")) {
//	                		updateStatusCode(-1);
//	                	}
	                	
	                	//Common.logOut(res);
	                    return res;
	                }
	            	
	            	

	            } finally {  
	            	httppost.releaseConnection();
	                response.close(); 
	            }  
	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (UnsupportedEncodingException e1) {  
	            e1.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	     
	        } catch(Exception e){
	     	   e.printStackTrace();
	        } 
	        return null;
	    }
	    
	    
	    public String getPicNum(String picUri) {
	    	try {
		   	    HttpGet httpget = new HttpGet(picUri);
		        httpget.addHeader("Connection","keep-alive");
		
		        httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");
		        httpget.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
		        httpget.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
		        httpget.addHeader("Accept-Language","zh-CN,zh;q=0.9");
		        httpget.addHeader("Host",ADDRESS.replace("https://", ""));

	            
		        CloseableHttpResponse response = execute(httpget); 
	       	 try {

	                // 打印响应状态    
	               // Common.logOut(response.getStatusLine()); 

	                File storeFile = new File(ACCOUNT+"AC.png");   //图片保存到当前位置
	                FileOutputStream output = new FileOutputStream(storeFile);  
	                //得到网络资源的字节数组,并写入文件  
	                
	              //  Common.logOut(response.getEntity());
	                
	                byte [] a = EntityUtils.toByteArray(response.getEntity());
	               // Common.logOut(bytesToHex(a));
	                output.write(a);  
	                output.close();  
	                
	                
	                
	                String url = "http://103.234.98.153:8089/api/tr-run/";
	                File file = new File(ACCOUNT+"AC.png");

                    HttpPost httpPost = new HttpPost(url);

                    // 创建MultipartEntityBuilder来构建多部分表单数据
                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    builder.addPart("file", new FileBody(file));  // 上传文件
                    builder.addPart("compress", new StringBody("0"));  // 其他表单数据

                    // 设置请求体
                    HttpEntity entity = builder.build();
                    httpPost.setEntity(entity);

                    // 执行请求并获取响应

                	response = httpclient.execute(httpPost);
                    // 获取响应体并转换为字符串
                    String responseString = EntityUtils.toString(response.getEntity());


                    
                    if(responseString.contains("raw_out")) {
                        ObjectMapper objectMapper = new ObjectMapper();

                        // 将 JSON 字符串解析为 JsonNode
                        JsonNode rootNode = objectMapper.readTree(responseString);

                        // 获取 "data" 节点
                        JsonNode dataNode = rootNode.path("data");

                        // 获取 "raw_out" 数组
                        JsonNode rawOutNode = dataNode.path("raw_out");

                        // 获取 "raw_out" 数组中的第一个元素
                        JsonNode firstRawOutNode = rawOutNode.get(0);

                        // 获取第二个元素（即 "1240"）
                        String extractedValue = firstRawOutNode.get(1).asText();

                        extractedValue = extractedValue.replace("^", "4");
                        extractedValue = extractedValue.replace("g", "8");
                        extractedValue = extractedValue.replace(">", "7");
                        extractedValue = extractedValue.replace(",", "8");
                        extractedValue = extractedValue.replace("o", "0");
                        extractedValue = extractedValue.replace("Z", "2");
                        extractedValue = extractedValue.replace(" ", "");

                        
                        if (extractedValue.matches("^\\d{4}$")) {
                            return extractedValue;
                        } 
                    }

//	        		File file = new File(ACCOUNT+"fuan.jpg");
//	        		ITesseract tesseract = new Tesseract();
//	        		tesseract.setDatapath("tessdata");
//	        		String result = "";
//	       			result = tesseract.doOCR(file);
//	       			result = result.replaceAll("\\s*|\r|\n|\t", "");
//	        		//Common.logOut(result);
//	       			
//	       			Header[] headers = response.getHeaders("Set-Cookie");
//	       			for (Header header : headers) {
//	       			    BasicClientCookie cookie = new BasicClientCookie(header.getName(), header.getValue());
//	       			    cookie.setDomain(httpget.getURI().getHost());
//	       			    cookie.setPath("/");
//	       			    cookieStore.addCookie(cookie);
//	       			}
	       			
	       			//cookieStore.addCookie((org.apache.http.cookie.Cookie) response.getFirstHeader("Set-Cookie"));
	       			
	                return "";
	       	 }catch(Exception e) {
	       		 e.printStackTrace();
	       	 }
	       	 finally{
	       		httpget.releaseConnection();
	       		 response.close(); 
	       	 }
	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (UnsupportedEncodingException e1) {  
	            e1.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	        } catch (Exception e) {
					e.printStackTrace();
			 }
	        
	   	return null;
	   }
	    
	    
//	    public String doPost(String url,String formparams, String cookies, HttpPost httppost) {
//	        return doPost(url, formparams,"UTF-8", cookies, httppost);
//	    }
//
//	    public String doPost(String url,String formparams,String charset, String cookies, HttpPost httppost) {
//
//
//	     // 创建httppost   
//	    	
//	    	try {
//	    	
//
//
//	        StringEntity requestEntity = new StringEntity(formparams,"utf-8");
//
//	           requestEntity.setContentEncoding("UTF-8");
//	           httppost.setEntity(requestEntity);
//
//
//	            
//	            
//	            
////	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
////	            
//	//
////	            
////	            
////	            
////	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
////	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
////	            httppost.setConfig(requestConfigtmp);
//	            
//	            CloseableHttpResponse response = execute(httppost);
//	            try {
//	                // 打印响应状态    
//	            	//setCookie(response);
//	            	//Common.logOut("设置cookie:" + strCookies);
//	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
//	            		String location = response.getFirstHeader("Location").getValue();
//	            		//Common.logOut(response.getStatusLine());
//	            		
//	            		
//	            		
//	            		if(location != null) {
//	            			return location;
//	            		}
//	            	}
//	            	
//	            	
//	            	
//	            	//Header headers[] = response.getHeaders("Content-Type");
//	            	
//	            	
//	                HttpEntity entity = response.getEntity(); 
//	                
//	                String res = "";
//	                
//	                if(url.contains("get_today_ft_league_wager.php") || url.contains("app/ft/get_today_ft_allbets_wager.php")){            		
//	                	res = new  String(EntityUtils.toString(entity).getBytes("ISO-8859-1"), "UTF-8");
//	                }else{
//	                	res = EntityUtils.toString(entity);
//	                }
//	                
//	                
//	                if(res != null && res.length() > 0 ){   
//
////	                	if(res.contains("logout_warn")) {
////	                		updateStatusCode(-1);
////	                	}
//	                	
//	                	//Common.logOut(res);
//	                    return res;
//	                }
//	            	
//	            	
//
//	            } finally {  
//	            	httppost.releaseConnection();
//	                response.close(); 
//	            }  
//	        } catch (ClientProtocolException e) {  
//	            e.printStackTrace(); 
//	        } catch (UnsupportedEncodingException e1) {  
//	            e1.printStackTrace(); 
//	        } catch (IOException e) {  
//	            e.printStackTrace(); 
//	     
//	        } catch(Exception e){
//	     	   e.printStackTrace();
//	        } 
//	        return null;
//	    }
	    
	    
	    public static String extractLocationHref(String html) {
	        Document doc = Jsoup.parse(html);
	        Elements scripts = doc.getElementsByTag("script");
	        
	        // 正则表达式匹配 location.href 的内容
	        Pattern pattern = Pattern.compile(
	            "location\\.href\\s*=\\s*['\"](.*?)['\"]\\s*;?",
	            Pattern.CASE_INSENSITIVE
	        );

	        for (Element script : scripts) {
	            String scriptContent = script.html();
	            Matcher matcher = pattern.matcher(scriptContent);
	            if (matcher.find()) {
	                return matcher.group(1);
	            }
	        }
	        return null; // 未找到返回null
	    }
	    
	    public int login(){// 1成功	 -1登录失败, -2维护 , -3账号异常, -4密码不正确	    	
	    	try{		  

	    		
	    		List<NameValuePair> params = new ArrayList<>();
	            params.add(new BasicNameValuePair("safecode", SC));
	            params.add(new BasicNameValuePair("act", "chkcode"));
	            
	            HttpPost httppost = new HttpPost(ADDRESS+"/index.php/Getdata");
	            
    	        httppost.addHeader("Accept-Language","Accept-Language: zh-CN");
    	        httppost.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
    	        httppost.addHeader("Accept-Encoding","gzip, deflate");
    	        httppost.addHeader("Connection","keep-alive");
    	        httppost.addHeader("Cache-Control","max-age=0");
    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    
    	
	    		
    	        String jsonResponse = doPost("", params, "",httppost);
    	        
                JSONObject data = new JSONObject(jsonResponse);
                if (data.optInt("s", 0) < 1) {
                    System.out.println("验证失败");
                    return -1;
                }
                
                // 3. 处理有效响应
                String token = data.getString("k");
                String[] urls = data.getString("u").split("\\|");
                
                // 4. 构造生成的链接
                for (String urlGroup : urls) {
                    if (urlGroup == null || urlGroup.isEmpty()) continue;
                    
                    String[] links = urlGroup.split(",");
                    for (int i = 0; i < links.length; i++) {
                        String validUrl = links[i] + "?token=" + token;
                        if(links[i].contains("g1"));{
                        	System.out.println("生成链接：" + validUrl);
                            
                            ADDRESSG = links[i];
                            break;
                        }
                        
                        
                        
                        // 5. 可以继续访问这些链接
                        // httpClient.execute(new HttpGet(validUrl));
                    }
                }
                
                //https://g1.acc8f.com/index.php/Login?getname=3&token=54F5FE69EBA5106B8F34EDBB962C7222
                String loginPage = doGet(ADDRESSG+"/index.php/Login?getname=3&token=" + token, "", "");
                
                
                String timeStr = System.currentTimeMillis()+"";
                httppost = new HttpPost(ADDRESSG+"/index.php/Login?t=" + timeStr);
                
                httppost.addHeader("Referer",ADDRESSG+"?token="+token);
                
        		List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
	        	loginParams.add(new BasicNameValuePair("username", ACCOUNT));
	        	loginParams.add(new BasicNameValuePair("pwd", PWD));
	        	loginParams.add(new BasicNameValuePair("token", token));
	        	loginParams.add(new BasicNameValuePair("act", "userlogin"));
	        	loginParams.add(new BasicNameValuePair("x", "35"));
	        	loginParams.add(new BasicNameValuePair("y", "18"));
	        	loginParams.add(new BasicNameValuePair("f", timeStr));
	        	
	        	String res = doPost("", loginParams, "",httppost);
	        	String uri = "";
	        	if(res.contains("location")) {
	        		uri = extractLocationHref(res);
	        	}
	        	
	        	String startPage = doGet(ADDRESSG+uri, "", "");
	        	if(startPage.contains("Welcome")) {
	        		Common.logOut(ACCOUNT + " 盈泰 login success " + uid); // group(1) 获取第一个捕获组
    	            
	        		updateStatusCode(1);
	        		return 1;
	        	}else {
	        		Common.logOut(ACCOUNT + " 盈泰 login failed " + startPage);		        	
		        	updateStatusCode(-1);
		        	return -1;
		        	
	        	}


	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    	updateStatusCode(-1);    	
	    	return -1;
	    }
	    
	    public void getLotteryIssueInfo() {
	    	try {	    		
	    		String res = doGet(ADDRESSG+"/index.php/report_index/head_menu.html", "", "");
	    		if(res.contains("期")) {
	    			//var num = '37期'
	    			//\\s*=\\s*
		    		Pattern pattern = Pattern.compile("var\\snum\\s=\\s\'(\\d+)期\'");
			        // 创建Matcher对象
			        Matcher matcher = pattern.matcher(res);
			        if (matcher.find()) {
    		            // 输出提取到的installments值
    		        	installments = matcher.group(1);
    		        	String formattedPeriod = String.format("%03d", Integer.parseInt(installments));
    		        	String currentYear = String.valueOf(Year.now().getValue()); // 获取当前年份
    		        	installments = currentYear + formattedPeriod;
    		        	
			        }
	    		}

	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    }
	    
	    public void getOldLotteryIssueInfo() {
	    	try {
	    		
	    		String res = doGet(ADDRESSG+"/index.php/report_index/head_menu.html", "", "");
	    		if(res.contains("期")) {
	    			//var num = '37期'
	    			//\\s*=\\s*
		    		Pattern pattern = Pattern.compile("var\\snum\\s=\\s\'(\\d+)期\'");
			        // 创建Matcher对象
			        Matcher matcher = pattern.matcher(res);
			        if (matcher.find()) {
    		            // 输出提取到的installments值
    		        	oldInstallments = matcher.group(1);
    		        	String formattedPeriod = String.format("%03d", Integer.parseInt(oldInstallments));
    		        	String currentYear = String.valueOf(Year.now().getValue()); // 获取当前年份
    		        	oldInstallments = currentYear + formattedPeriod;
    		        	
			        }
	    		}

	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    }
	    
	    public void getActualData() {
	    	try {
	    		JSONObject currentData = new JSONObject();
	    		currentData.put("msg", "FAILED");
	    		currentData.put("account", ACCOUNT);
	    		
	    		List<NameValuePair> params = new ArrayList<>();
	            params.add(new BasicNameValuePair("cai", "4"));
	            
	            HttpPost httppost = new HttpPost(ADDRESSG+"/index.php/index/top.html");
	            
    	        httppost.addHeader("Accept-Language","Accept-Language: zh-CN");
    	        httppost.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
    	        httppost.addHeader("Accept-Encoding","gzip, deflate");
    	        httppost.addHeader("Connection","keep-alive");
    	        httppost.addHeader("Cache-Control","max-age=0");
    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    

    	        String jsonResponse = doPost("", params, "",httppost);
    	        
    	        
	    		
	    		getLotteryIssueInfo();
	    		
	    		//https://g1.acc8f.com/index.php/report_index/index.html
    			String res = doGet(ADDRESSG+"/index.php/report1/index/nav/1/pid/1.html", "", "");

    			if(res.contains("特A")) {
    		        Document doc = Jsoup.parse(res);
    		        // 选择所有class="content"的<tr>元素
    		        
    		        JSONArray ja2 = new JSONArray();
    		        Elements rows = doc.select("tr.content");
    		        for (Element row : rows) {
    		            Elements tds = row.select("td");
    		            if (tds.size() >= 5) { // 确保有足够的列
    		                // 提取第二个<td>中的"特XX"（索引从0开始）
 
    		                String te = tds.get(1).select("b").text();
    		                
    		                // 提取第五个<td>中的数值（索引4）
    		                String value = tds.get(4).text();
    		                
    		                if (!te.isEmpty() && !value.isEmpty()) {
         	        			 JSONObject newItem = new JSONObject();
          	        			 newItem.put("amount", Integer.parseInt(value.replace(",", "")));
          	        			 newItem.put("contents", te.replace("特", ""));
          	        			 newItem.put("earnings", 0);
          	        			 ja2.put(newItem);
    		                }
    		            }
    		        }


    				
  	    	         currentData.put("data", ja2);


    			}else {
    				updateStatusCode(-1);
    			}
    			
    			//https://g1.acc8f.com/index.php/report7/index/nav/7/pid/5.html
    			
    			res = doGet(ADDRESSG+"/index.php/report7/index/nav/7/pid/5.html", "", "");

    			if(res.contains("YXWS")) {
    		        Document doc = Jsoup.parse(res);
    		        // 选择所有class="content"的<tr>元素
    		        
    		        JSONArray ja2 = new JSONArray();
    		        Elements rows = doc.select("tr.content");
    		        for (Element row : rows) {
    		            Elements tds = row.select("td");
    		            if (tds.size() >= 5) { // 确保有足够的列
    		                // 提取第二个<td>中的"特XX"（索引从0开始）
 
    		                String te = tds.get(1).select("b").text();
    		                
    		                boolean isNumeric = te.matches(".*\\d.*");
    	    				if(isNumeric) {
    	    					continue;
    	    				}
    		                
    		                // 提取第五个<td>中的数值（索引4）
    		                String value = tds.get(4).text();
    		                
    		                if (!te.isEmpty() && !value.isEmpty()) {
         	        			 JSONObject newItem = new JSONObject();
          	        			 newItem.put("amount", Integer.parseInt(value.replace(",", "")));
          	        			 newItem.put("contents", te.replace("特", ""));
          	        			 newItem.put("earnings", 0);
          	        			 ja2.put(newItem);
    		                }
    		            }
    		        }


    				
  	    	         currentData.put("msg", "SUCCESS");
  	    	         currentData.put("yxdata", ja2);
  	    	         currentData.put("grabtime", System.currentTimeMillis());
  	    	         currentData.put("currIssue", installments);
  	    	         currentData.put("currOpenTime", 0);
  	    	         currentData.put("sellTime", 0);
  	    	         YingtaiManager.dataJArray.put(currentData);
  	    	         Common.logOut(ACCOUNT + " 盈泰 ActualData success" );

    			}else {
    				updateStatusCode(-1);
    			}
    	        
	    	}catch(Exception e) {
	    		updateStatusCode(-1);
	    		e.printStackTrace();
	    	}
	    }
	    
	    
	    public void getOldActualData() {
	    	try {
	    		JSONObject currentData = new JSONObject();
	    		currentData.put("msg", "FAILED");
	    		currentData.put("account", ACCOUNT);
	    		//https://g1.acc8f.com/index.php/index/top.html
	    		
	    		List<NameValuePair> params = new ArrayList<>();
	            params.add(new BasicNameValuePair("cai", "0"));
	            
	            HttpPost httppost = new HttpPost(ADDRESSG+"/index.php/index/top.html");
	            
    	        httppost.addHeader("Accept-Language","Accept-Language: zh-CN");
    	        httppost.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
    	        httppost.addHeader("Accept-Encoding","gzip, deflate");
    	        httppost.addHeader("Connection","keep-alive");
    	        httppost.addHeader("Cache-Control","max-age=0");
    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    

    	        String jsonResponse = doPost("", params, "",httppost);
    	        
    	        
	    		
	    		getOldLotteryIssueInfo();
	    		
	    		//https://g1.acc8f.com/index.php/report_index/index.html
    			String res = doGet(ADDRESSG+"/index.php/report1/index/nav/1/pid/1.html", "", "");

    			if(res.contains("特A")) {
    		        Document doc = Jsoup.parse(res);
    		        // 选择所有class="content"的<tr>元素
    		        
    		        JSONArray ja2 = new JSONArray();
    		        Elements rows = doc.select("tr.content");
    		        for (Element row : rows) {
    		            Elements tds = row.select("td");
    		            if (tds.size() >= 5) { // 确保有足够的列
    		                // 提取第二个<td>中的"特XX"（索引从0开始）
 
    		                String te = tds.get(1).select("b").text();
    		                
    		                // 提取第五个<td>中的数值（索引4）
    		                String value = tds.get(4).text();
    		                
    		                if (!te.isEmpty() && !value.isEmpty()) {
         	        			 JSONObject newItem = new JSONObject();
          	        			 newItem.put("amount", Integer.parseInt(value.replace(",", "")));
          	        			 newItem.put("contents", te.replace("特", ""));
          	        			 newItem.put("earnings", 0);
          	        			 ja2.put(newItem);
    		                }
    		            }
    		        }


    				
  	    	         currentData.put("msg", "SUCCESS");
  	    	         currentData.put("data", ja2);
  	    	         currentData.put("grabtime", System.currentTimeMillis());
  	    	         currentData.put("currIssue", oldInstallments);
  	    	         currentData.put("currOpenTime", 0);
  	    	         currentData.put("sellTime", 0);
  	    	         YingtaiManager.oldDataJArray.put(currentData);
  	    	         Common.logOut(ACCOUNT + " 盈泰 ActualData success old" );

    			}else {
    				updateStatusCode(-1);
    			}
    			

    	        
	    	}catch(Exception e) {
	    		updateStatusCode(-1);
	    		e.printStackTrace();
	    	}
	    }
}


